<template>
    <div>
        <div v-if="isDebug" style="padding: 20px;">
            <p> {{ imgReading }} </p>
            <p> {{ uploadImgIng }} </p>
        </div>
        <div class="gh-upload-image">
            <md-image-reader
                    :name='mdImgReader'
                    @select="onReaderSelect"
                    @complete="onReaderComplete"
                    @error="onReaderError"
                    :is-camera-only="isCameraOnly||isCameraPre"
                    :is-multiple="isMultiple"
                    :amount="imgCount"
                    v-if="cameraHandlerType.includes('page')"
            ></md-image-reader>
            <div @click="wxUpload">
                <slot></slot>
            </div>
            <div id="container">
                <div id="selectfiles"></div>
            </div>
        </div>
    </div>
</template>

<script>
  /* eslint-disable */
  import { ImageReader } from 'mand-mobile'
  // import imageProcessor from 'mand-mobile/lib/image-reader/image-processor' // 图片处理插件，用法参考#imageProcessor
  import http from '@/utils/http'

  const WXAPPID = process.env.VUE_APP_WX_APPID
  const CUSTOMER = process.env.VUE_APP_BASE_CUSTOMER
  // const BASIS = process.env.VUE_APP_BASIS_URL
  // const BASIS = 'http://10.56.40.91:8001/restful/basis'
  const BASIS = 'https://dat-m.huaruisales.com/restful/basis'
  export default {
    name: 'gh-upload-image',
    components: {
      [ ImageReader.name ]: ImageReader,
    },
    props: {
      pmdCamera: {
        /*
        * 是否只使用手机原生相机
        * */
        type: Boolean,
        default(){
          return false
        }
      },
      /*
      * 是否只打开相机
      * */
      isCameraOnly: {
        type: Boolean,
        default(){
          return false
        }
      },
      /*
      * 是否只打开前置相机 不生效无法使用
      * */
      isCameraPre: {
        type: Boolean,
        default(){
          return false
        }
      },
      /*
      图片属性
      * page原生相机的情况下 图片压缩参数
      * quality 压缩比例
      * width 宽度
      * height 高度
      * */
      imageAttribute: {
        type: Object,
        default(){
          return {
            quality: 0.5
          }
        }
      },
      imageCount: { // 图片数量 暂时无法使用  暂时后端不支持多个图片上传
        type: Number,
        default(){
          return 1
        }
      },
      type: { // 平台类型
        type: String,
        default(){
          return ''
        }
      },
      system: { // 系统类型
        type: String,
        default(){
          return ''
        }
      },
      businessType: { // 业务类型
        type: String,
        default(){
          return ''
        }
      },
      uploadOss: {
        type: Boolean,
        default(){
          return true
        }
      },
      upname: {   // 组件的名字标识,方便多个组件用同一回调时区分不同组件的回调
        type: String,
        default: 'imgupload'
      }
    },
    watch: {
      uploadOss: {
        deep: true,
        immediate: true,
        handler(n){
          if(n){
            this.load_script_fun('https://cdn1.huaruisales.com/ghss/upload.min.js').then(res => {
              console.log(1)
            }).catch(error => {
            })
          }
        }
      }
    },
    data(){
      return {
        imgSrcList: [],
        fileIdList: [],
        uploader: null,
        wx: null,
        imgReading: '', // 图片准备阶段
        uploadImgIng: '', // 图片上传阶段
        isDebug: false
      }
    },
    computed: {
      // md-ui唯一标识
      mdImgReader(){
        let id = this.only()
        return `md-img-reader-${id}`
      },
      // md-ui 图片多选
      isMultiple(){
        if(this.imgCount > 1){
          return true
        } else{
          return false
        }
      },
      // 打开相机或者相册的类型
      cameraHandlerType(){
        if(this.pmdCamera){
          return 'page'
        } else{
          let guat = this.getUserBrowserType()
          console.log('相机类型已默认为' + guat)
          return guat
        }
      },
      // 可选择的图片数量
      imgCount(){
        if(this.imageCount >= 1 && this.imageCount <= 9){
          return this.imageCount
        } else{
          console.log('图片数量不符合规则,已默认为1')
          return 1
        }
      },
      sizeType(){
        // 图片类型 original:原图 compressed:压缩图
        if(this.imageAttribute.quality != 1){
          return [ 'compressed' ]
        } else{
          return [ 'original', 'compressed' ]
        }
      },
    },
    created(){
      this.load_script_fun('https://cdn1.huaruisales.com/ghss/imgZipPrd.js').then(res => {
        console.log('算法加载完成', res)
      }).catch(error => {
      })
    },
    mounted(){
      console.log('系统参数', this.type, this.system, this.businessType)
      console.log('图片压缩参数', this.imageAttribute)
      console.log('相机类型', this.cameraHandlerType)
      console.log('只打开相机', this.isCameraOnly)
      console.log('只打开前置相机', this.isCameraPre)
      console.log('开启oss上传', this.uploadOss)
      if(this.isCameraPre){
        const carme = document.getElementsByName(this.mdImgReader)[ 0 ]
        carme.setAttribute('capture', 'user')
        console.log(carme)
      }
    },
    methods: {
      // 处理旋转图片   旋转图片使用
      handlerRotateImg(src, Orientation){
        let that = this
        // if ( Orientation != '' && Orientation != 1 ) {
        return new Promise((resolve, reject) => {
          let image = new Image()
          image.src = src
          image.onload = () => {
            try{
              let canvas = document.createElement('canvas')
              let ctx = canvas.getContext('2d')
              let width = image.width, height = image.height
              canvas.width = width
              canvas.height = height
              ctx.drawImage(image, 0, 0, width, height)
              //如果方向角不为1，都需要进行旋转 added by lzk
              // 拍的时候正常拍是6
              // 逆时针转了90°是1
              // 顺时针转了90°是3
              // 倒着拍是8
              console.log('旋转处理' + Orientation)
              switch(Orientation){
                case 3:
                  ctx.rotate(180 * Math.PI / 180)
                  ctx.drawImage(image, -width, -height, width, height)
                  break
                case 8:
                  ctx.rotate(90 * Math.PI / 180)
                  ctx.drawImage(image, 0, -width, height, width)
                  break
                case 6:
                  ctx.rotate(270 * Math.PI / 180)
                  ctx.drawImage(image, -height, 0, height, width)
                  break
                case 2:
                  ctx.translate(width, 0)
                  ctx.scale(-1, 1)
                  ctx.drawImage(image, 0, 0, width, height)
                  break
                case 4:
                  ctx.translate(width, 0)
                  ctx.scale(-1, 1)
                  ctx.rotate(180 * Math.PI / 180)
                  ctx.drawImage(image, -width, -height, width, height)
                  break
                case 5:
                  ctx.translate(width, 0)
                  ctx.scale(-1, 1)
                  ctx.rotate(90 * Math.PI / 180)
                  ctx.drawImage(image, 0, -width, height, width)
                  break
                case 7:
                  ctx.translate(width, 0)
                  ctx.scale(-1, 1)
                  ctx.rotate(270 * Math.PI / 180)
                  ctx.drawImage(image, -height, 0, height, width)
                  break
                default:
                  ctx.drawImage(image, 0, 0, width, height)
              }
              let UA = that.getUserMobileType(), dataUrl
              if(UA.oldIOS || UA.oldAndroid || UA.mQQBrowser || !navigator.userAgent){
                /* global JPEGEncoder */
                try{
                  let encoder = new JPEGEncoder()
                  let newImg = ctx.getImageData(0, 0, width, height)
                  dataUrl = encoder.encode(newImg)
                } catch(e){
                  dataUrl = canvas.toDataURL('image/jpeg')
                }
              } else{
                dataUrl = canvas.toDataURL('image/jpeg')
              }
              let blob = that.base64ToBlod(dataUrl)
              resolve({ rDataUrl: dataUrl, rBlob: blob })
            } catch(e){
              reject(e)
            }
          }
        })
      },
      //  base64转ArrayBuffer   旋转图片使用
      base64ToArrayBuffer(base64){
        base64 = base64.replace(/^data\:([^\;]+)\;base64,/gmi, '')
        let binary = atob(base64),
          len = binary.length,
          buffer = new ArrayBuffer(len),
          view = new Uint8Array(buffer)
        for(let i = 0; i < len; i++){
          view[ i ] = binary.charCodeAt(i)
        }
        return buffer
      },
      // 获取图片旋转信息   旋转图片使用
      getOrientation(arrayBuffer){
        let view = new DataView(arrayBuffer)
        if(view.getUint16(0, false) != 0xFFD8){
          return -2
        }
        let length = view.byteLength, offset = 2
        while(offset < length){
          let marker = view.getUint16(offset, false)
          offset += 2
          if(marker == 0xFFE1){
            if(view.getUint32(offset += 2, false) != 0x45786966){
              return -1
            }
            let little = view.getUint16(offset += 6, false) == 0x4949
            offset += view.getUint32(offset + 4, little)
            let tags = view.getUint16(offset, little)
            offset += 2
            for(let i = 0; i < tags; i++){
              if(view.getUint16(offset + ( i * 12 ), little) == 0x0112){
                return view.getUint16(offset + ( i * 12 ) + 8, little)
              }
            }
          } else if(( marker & 0xFF00 ) != 0xFF00){
            break
          } else{
            offset += view.getUint16(offset, false)
          }
        }
        return -1
      },
      // base64转blod   旋转图片使用
      base64ToBlod(base64){
        let arr = base64.split(','),
          //注意base64的最后面中括号和引号是不转译的
          _arr = arr[ 1 ].substring(0, arr[ 1 ].length - 2),
          mime = arr[ 0 ].match(/:(.*?);/)[ 1 ],
          bstr = atob(_arr),
          n = bstr.length,
          u8arr = new Uint8Array(n)
        while(n--){
          u8arr[ n ] = bstr.charCodeAt(n)
        }
        return new Blob([ u8arr ], {
          type: mime
        })
      },
      // blod转file   转换文件使用 : 处理不兼容file文件
      boldToFile(bold, file){
        // 强制转换为jpeg的形式 然后后缀是jpg即可
        let fileName = this.only('.jpg')
        try{
          console.log('try-true')
          return new File([ bold ], fileName, { type: 'image/jpeg' /*lastModified : Date.now ()*/ })
        } catch(e){
          console.log('try-false', e)
          let d = new Date()
          bold.lastModifiedDate = d
          bold.lastModified = d.getTime()
          bold.name = fileName
          bold.type = 'image/jpeg'
          return bold
        }
      },
      // 动态加载js
      load_script_fun(src){
        return new Promise((resolve, reject) => {
          let d = document
          let dom = d.getElementById(src)

          let handlerError = function(e){
            reject(e)
          }
          if(dom){
            // 已经存在
            if(dom.isSuccess){
              resolve(3)
              return
            }
            let handlerDomLoad = function(e){
              if(e.type === 'load'){
                // 加载完成
                resolve(2, e)
              }
            }
            dom.addEventListener('load', handlerDomLoad)
            dom.addEventListener('readystatechange', handlerDomLoad)
            dom.addEventListener('error', handlerError, { once: true })
            dom.addEventListener('abort', handlerError, { once: true })
            return
          }
          let script = d.createElement('script')
          script.charset = 'utf-8'
          script.type = 'text/javascript'
          script.src = src
          script.id = src
          let scripts = d.getElementsByTagName('script')[ 0 ]
          scripts.parentNode.insertBefore(script, scripts)
          let handlerLoad = function(e){
            if(e.type === 'load'){
              // 加载完成
              script.isSuccess = true
              resolve(1, e)
            }
          }
          script.addEventListener('load', handlerLoad)
          script.addEventListener('readystatechange', handlerLoad)
          script.addEventListener('error', handlerError, { once: true })
          script.addEventListener('abort', handlerError, { once: true })
        })
      },
      // 生成唯一id
      only(text = ''){
        let diff = 0
        do
          diff = Math.floor(Math.random() * 1000000000)
        while(diff < 100000000)
        return '' + new Date().getTime() + diff + text
      },
      // 获取当前浏览器类型
      getUserBrowserType(){
        let uausto = navigator.userAgent.toLowerCase()
        // console.log ( navigator.userAgent , uausto )
        if(uausto.indexOf('app_ios') != -1){
          if(uausto.indexOf('ghapp_ios_v2') != -1){
            return 'ios_v2'
          } else{
            return 'ios'
          }
        } else if(uausto.indexOf('app_android') != -1){
          if(uausto.indexOf('ghapp_android_v2') != -1){
            return 'android_v2'
          } else{
            return 'android'
          }
        } else if(uausto.match(/MicroMessenger/i) == 'micromessenger'){
          if(uausto.indexOf('wxwork') != -1){
            return 'wxwork'
          } else{
            return 'wx'
          }
        } else if(uausto.match(/AlipayClient/i) == 'alipayclient'){
          return 'alipay'
        } else if(uausto.match(/MPBank/i) == 'mpbank'){
          return 'cmb'
        } else{
          return 'page'
        }
      },
      // 获取手机类型
      getUserMobileType(){
        let userAgent = navigator.userAgent
        // let isAndroid = u.indexOf ( 'Android' ) > -1 || u.indexOf ( 'Linux' ) > -1 //g
        // let isIOS = !!u.match ( /\(i[^;]+;( U;)? CPU.+Mac OS X/ ) //ios终端
        // if ( isAndroid ) {
        //   return 'android'
        // } else if ( isIOS ) {
        //   return 'ios'
        // } else return 'other'
        let isOldIos = /OS (\d)_.* like Mac OS X/g.exec(userAgent)
        let isOldAndroid = /Android (\d.*?);/g.exec(userAgent) || /Android\/(\d.*?) /g.exec(userAgent)
        return {
          oldIOS: isOldIos ? +isOldIos.pop() < 8.3 : false,
          oldAndroid: isOldAndroid ? +isOldAndroid.pop().substr(0, 3) < 4.5 : false,
          ios: /\(i[^;]+;( U;)? CPU.+Mac OS X/.test(userAgent),
          android: /Android/g.test(userAgent),
          mQQBrowser: /MQQBrowser/g.test(userAgent)
        }
      },
      // 解密
      crypto(encryptedStr){
        const CryptoJS = require('crypto-js')
        let key = CryptoJS.enc.Utf8.parse('12A0FEA40A48B4A9')
        let encryptedHexStr = CryptoJS.enc.Base64.parse(encryptedStr)
        let encryptedBase64Str = CryptoJS.enc.Base64.stringify(encryptedHexStr)
        let decryptedData = CryptoJS.AES.decrypt(encryptedBase64Str, key, {
          mode: CryptoJS.mode.ECB,
          padding: CryptoJS.pad.Pkcs7
        })
        return decryptedData.toString(CryptoJS.enc.Utf8)
      },
      // 图片选择完成事件，还未开始读取
      onReaderSelect(name, { files }){
        // console.log ( name , files )
        this.failEmit(5)
      },
      // 图片选择读取完成事件
      onReaderComplete(name, { dataUrl, blob, file }){
        this.imgReading = '1.图片选择完成'
        let formdata = new FormData()
        formdata.append('type', this.type)
        formdata.append('system', this.system)
        formdata.append('businessType', this.businessType)
        this.failEmit(6)
        console.log(navigator.userAgent)
        if(true){
          let quality = 0.5
          if(this.imageAttribute.quality < 0.1){
            quality = 0.1
          } else if(this.imageAttribute.quality > 0.9){
            quality = 0.9
          } else{
            quality = this.imageAttribute.quality
          }
          let options = {
            quality,
            // ingnoreOrientation:false
          }
          if(this.imageAttribute.width){
            options.width = this.imageAttribute.width
          }
          if(this.imageAttribute.height){
            options.height = this.imageAttribute.height
          }
          console.log('压缩参数', options)
          console.log('原文件base64长度' + dataUrl.length)
          console.log('原文件blob-size' + blob.size)
          console.log(blob)
          console.log('原文件file-size' + file.size)
          console.log(file)
          this.imgReading += '2.图片需要压缩' + JSON.stringify(options)
          // let AUrl = dataUrl
          // imageProcessor({
          //   dataUrl,
          //   ...options
          // }).then(({ dataUrl, blob }) => {
          lrz(file, options).then(({ base64, file }) => {
            dataUrl = base64
            console.log('压缩文件base64长度' + dataUrl.length)
            blob = file
            console.log('压缩文件blob-size' + blob.size)
            console.log(blob)
            // let UA = this.getUserMobileType()
            // if ( UA.oldIOS || UA.ios ) {
            //   this.handlerRotateImg ( dataUrl , this.getOrientation ( this.base64ToArrayBuffer ( AUrl ) ) ).then ( ( { rDataUrl , rBlob } ) => {
            //     console.log ( '旋转完成' )
            //     dataUrl = rDataUrl
            //     blob = rBlob
            //   } ).catch ( e => {
            //     console.log ( '旋转出错' )
            //   } )
            // }
            // console.log('转换前', blob, file)
            // blob = this.boldToFile(blob, file)
            // console.log('转换后', blob)
            console.log('压缩添加前')
            this.imgReading += '3.图片压缩完成'
            this.failEmit(7)
            if(this.uploadOss){
              this.imgReading += '4.压缩图片准备上传oss'
              this.handlerOssUpload(blob, dataUrl)
            } else{
              // 使用压缩后的表单和图片
              formdata.append('file', blob, blob.name)
              this.imgReading += '4.压缩图片准备上传国华服务器'
              this.uploaderCommon(formdata, dataUrl)
            }
          })
        } else{
          console.log('不压缩添加前')
          this.failEmit(7)
          if(this.uploadOss){
            this.imgReading += '2.图片准备上传oss'
            this.handlerOssUpload(file, dataUrl)
          } else{
            // 使用正常表单和图片
            formdata.append('file', file, file.name)
            this.imgReading += '2.图片准备上传国华服务器'
            this.uploaderCommon(formdata, dataUrl)
          }
        }
      },
      // page普通图片上传
      uploaderCommon(data, dataUrl){
        this.failEmit(8)
        this.uploadImgIng = '1.国华服务器上传图片已准备'
        http.post(`${BASIS}/uploader/common`,
          {
            data: data,
            // contentType : 'form'
          }).then(res => {
          if(res.resultCode == '0'){
            this.uploadImgIng = '2.国华服务器上传图片已完成'
            this.successEmit({ fileId: res.fileId, imgSrc: dataUrl })
          } else{
            this.uploadImgIng = '2.国华服务器上传图片已失败'
            this.failEmit(2)
          }
          console.log('/uploader/common接口参数', res)
        }).catch(e => {
          console.log('/uploader/common接口错误', e)
          this.failEmit(1)
        })
      },
      // oss图片上传处理
      handlerOssUpload(data, src){
        this.imgSrcList = []
        this.fileIdList = []
        this.uploaderOssInit()
        this.uploadImgIng = '1.oss上传图片已准备'
        this.uploaderOssConfig(data, src)
      },
      // 上传oss配置
      uploaderOssConfig(data, src){
        return new Promise((resolve, reject) => {
          http.post(`${BASIS}/oss/signature`,
            {
              data: {
                type: this.type,
                system: this.system,
                businessType: this.businessType
              },
              // contentType : 'form'
            }).then(res => {
            console.log('/oss/signature', res)
            if(res.resultCode == '0'){
              this.uploadImgIng += '2.oss上传图片签名已获取'
              let { accessId, policy, host, signature, dir, fileId } = res
              // let str = ( '' + data.name ).split('.')
              let keyName = this.crypto(fileId)
              let handlerName = keyName.split('@')[ 0 ]
              console.log(keyName, handlerName)
              let option = {
                url: host,
                multipart_params: {
                  // key: dir + handlerName + '.' + str[ str.length - 1 ], // 文件路径/文件名.后缀
                  key: dir + handlerName + '.jpg', // 文件路径/文件名.后缀
                  policy: policy,
                  OSSAccessKeyId: accessId,
                  success_action_status: '200', //让服务端返回200,不然，默认会返回204
                  signature: signature
                }
              }
              console.log('option', option)
              this.uploader.setOption(option)
              console.log('oss添加前', data)
              this.uploader.addFile(data, data.name)
              this.fileIdList.push(fileId)
              this.imgSrcList.push(src)
              setTimeout(() => {
                this.failEmit(8)
                this.uploadImgIng += '3.oss上传图片已开始'
                this.uploader.start()
              }, 200)
            } else{
              this.failEmit(2)
            }
          }).catch(e => {
            console.log('/oss/signature接口错误', e)
            this.failEmit(1)
          })
        })
      },
      // page OSS图片上传
      uploaderOssInit(){
        if(this.uploader == null){
          this.uploader = new plupload.Uploader({
            runtimes: 'html5,html4',
            browse_button: 'selectfiles',
            container: document.getElementById('container'),
            url: 'http://oss.aliyuncs.com',
            max_retries: 0, // 失败后重试的次数
            init: {
              Init: (up) => {
                this.uploader = up
                console.log('上传init')
              },
              PostInit: (up) => {
                this.uploader = up
                console.log('上传初始化')
              },
              FilesAdded: (up, files) => {
                this.uploader = up
                // console.log ( '上传文件的队列发生变化' , files )
              },
              UploadFile: (up, file) => {
                this.uploader = up
                // console.log ( '文件开始上传' , file , file.percent )
              },
              UploadProgress: (up, file) => {
                this.uploader = up
                // console.log ( '文件的上传进度' , file )
              },
              FileUploaded: (up, file, res) => {
                /*
                * res
                * response：服务器返回的文本
                * responseHeaders：服务器返回的头信息
                * status：服务器返回的http状态码，比如200
                * */
                this.uploader = up
                // console.log ( '文件上传完成' , file , res )
              },
              UploadComplete: (up, files) => {
                // console.log ( '所有文件上传完成' , files )
                console.log(up)
                this.uploader = up
                this.uploader.destroy()
                this.uploader = null
                this.uploadImgIng += '4.oss上传图片已完成'
                this.successEmit({ fileId: this.fileIdList[ 0 ], imgSrc: this.imgSrcList[ 0 ] })
              },
              Error: (up, err) => {
                /*
                * err
                * code：错误代码，具体请参考plupload上定义的表示错误代码的常量属性
                * file：与该错误相关的文件对象
                * message：错误信息
                * */
                console.log('文件上传错误')
                this.uploadImgIng += '4.oss上传图片已失败'
                this.uploader = up
                this.uploader.destroy()
                this.uploader = null
                this.failEmit(4)
              },
              Destroy: (up) => {
                console.log('上传销毁')
                if(this.uploader != null){
                  this.uploader = null
                }
              }
            }
          })
          this.uploader.init()
        }
      },
      // 成功回调
      successEmit(data){
        data.upname = this.upname
        this.$emit('success', data)
      },
      // 失败回调
      failEmit(data){
        let error = [
          { code: '0', message: '', type: '' },
          { code: '1', message: '网络错误', type: 'Error' },
          { code: '2', message: '接口处理错误', type: 'Error' },
          { code: '3', message: '图片读取错误', type: 'Error' },
          { code: '4', message: '图片上传错误', type: 'Error' },
          { code: '5', message: '选择图片准备中', type: 'Loading' },
          { code: '6', message: '图片选择完成', type: 'Loading' },
          { code: '7', message: '图片处理中', type: 'Loading' },
          { code: '8', message: '图片上传中', type: 'Loading' },
          { code: '9', message: '用户完成打开图片', type: 'Complete' }
        ]
        let ed = error[ data ]
        ed.upname = this.upname
        this.$emit('state-change', ed)
      },
      // 图片选择读取失败事件
      onReaderError(name, { msg }){
        console.log('图片读取失败', msg)
        this.failEmit(3)
      },
      // 处理图片选择
      handlerSelectImg(){
      },
      // 微信图片上传
      wxUpload(){
        if(this.cameraHandlerType.includes('wx')){
          this.failEmit(5)
          this.wx = require('weixin-js-sdk')
          this.imgSrcList = []
          this.fileIdList = []
          this.wxInitParams().then(res => {
            console.log('255', res)
            this.imgReading = '1.微信上传图片签名获取完毕'
            return this.wxConfig(res)
          }).then(() => {
            this.wxChooseImage()
          }).catch(() => {
            console.log('249')
            this.failEmit(3)
          })
        }
      },
      //微信验签
      wxInitParams(){
        return http.post(`${CUSTOMER}/common/initParams`,
          {
            data: {
              shareUrl: window.location.href,
              type: this.type,
              system: this.system,
              businessType: this.businessType,
              thirdType: 'wx'
            },
            contentType: 'form'
          })
      },
      // 微信配置
      wxConfig(params){
        this.wx.config({
          debug: false,
          appId: WXAPPID,
          timestamp: params.timestamp,
          nonceStr: params.nonceStr,
          signature: params.signature,
          jsApiList: [ 'chooseImage', 'uploadImage', 'getLocalImgData' ]
        })
        return new Promise((resolve, reject) => {
          this.wx.ready(() => {
            this.imgReading += '2.微信打开相册已就绪'
            resolve()
          })
          this.wx.error((e) => {
            console.log('微信error', e)
            this.imgReading += '2.微信打开相册失败'
            reject()
          })
        })
      },
      // 微信打开相机获取图片
      wxChooseImage(){
        let that = this
        that.wx.chooseImage({
          count: that.imgCount,
          sizeType: that.sizeType,
          sourceType: that.isCameraOnly || that.isCameraPre ? [ 'camera' ] : [ 'album', 'camera' ],
          success(res){
            that.imgReading += '3.微信已打开相册获取到图片'
            if(res != null && res.localIds && res.localIds.length > 0){
              setTimeout(() => {
                that.failEmit(6)
                that.wxUploadImage(res.localIds)
              }, 100)
            } else{
              console.log('299')
              that.failEmit(3)
            }
          },
          fail: () => {
            console.log('304')
            that.failEmit(3)
          },
          complete: () => {
            console.log('308')
            that.failEmit(9)
          }
        })
      },
      // 微信上传图片
      wxUploadImage(localIds){
        let that = this
        let localId = localIds.shift()
        if(!localId){
          console.log('316')
          that.failEmit(3)
          return
        }
        that.wx.uploadImage({
          localId: localId, // 需要上传的图片的本地ID，由chooseImage接口获得
          isShowProgressTips: 1, // 默认为1，显示进度提示
          success: function(res){
            if(res && res.serverId){
              that.imgReading += '4.微信图片已经上传到微信服务器'
              // that.fileIdList.push ( res.serverId )
              that.failEmit(7)
              if(!window.__wxjs_is_wkwebview){
                // 如果是安卓的则可以直接用localId直接显示
                that.imgSrcList.push(localId)
                if(localIds && localIds.length == 0){
                  that.imgReading += '5.微信安卓手机换取国华文件ID'
                  that.thirdFile(res.serverId)
                  // that.successEmit ( { fileId : that.fileIdList[ 0 ] , imgSrc : that.imgSrcList[ 0 ] } )
                } else if(localIds && localIds.length > 0){
                  setTimeout(() => {
                    that.wxUploadImage(localIds)
                  }, 300)
                }
              } else{
                // 否则是ios的需要读取本地图片后再显示
                that.wx.getLocalImgData({
                  localId: localId, // 图片的localID
                  success: (iosres) => {
                    if(iosres && iosres.localData){
                      that.imgSrcList.push(iosres.localData)
                      if(localIds && localIds.length == 0){
                        that.imgReading += '5.微信苹果手机换取国华文件ID'
                        that.thirdFile(res.serverId)
                        // that.successEmit ( { fileId : that.fileIdList[ 0 ] , imgSrc : that.imgSrcList[ 0 ] } )
                      } else if(localIds && localIds.length > 0){
                        setTimeout(() => {
                          that.wxUploadImage(localIds)
                        }, 300)
                      }
                    } else{
                      console.log('351')
                      that.failEmit(3)
                    }
                  },
                  fail: () => {
                    console.log('356')
                    that.failEmit(3)
                  }
                })
              }
            } else{
              console.log('362')
              that.failEmit(4)
            }
          },
          fail: () => {
            console.log('367')
            that.failEmit(4)
          }
        })
      },
      // 微信文件id转换国华文件id
      thirdFile(thirdFileId){
        this.failEmit(8)
        http.post(`${BASIS}/third/file`,
          {
            data: {
              type: this.type,
              system: this.system,
              businessType: this.businessType,
              thirdFileId,
              thirdType: 'wx'
            },
            // contentType : 'form'
          }).then(res => {
          if(res.resultCode == '0'){
            this.imgReading += '6.微信换取国华文件ID完成并返回'
            this.successEmit({ fileId: res.fileId, imgSrc: this.imgSrcList[ 0 ] })
          } else{
            this.imgReading += '6.微信换取国华文件ID失败'
            this.failEmit(2)
          }
          console.log('/third/file接口参数', res)
        }).catch(e => {
          console.log('/third/file接口错误', e)
          this.failEmit(1)
        })
      },
      // 图片根据id预览url地址
      previewFile(fileId){
        return new Promise((resolve, reject) => {
          http.post(`${BASIS}/preview/file`,
            {
              data: {
                type: this.type,
                system: this.system,
                businessType: this.businessType,
                fileId,
              },
              // contentType : 'form'
            }).then(res => {
            if(res.resultCode == '0'){
              resolve(res.fileUrl)
            } else{
              reject('接口错误')
            }
          }).catch(error => {
            reject('网络错误')
          })
        })
      },

    }
  }
</script>
<style lang="less" scoped>
    .gh-upload-image {
        display: inline-block;
        /*width: 100%;*/
        position: relative;
        /deep/ input {
            padding: 0;
            margin: 0;
        }
    }
</style>
